/* Copyright 2014 Jan Wolter */
#include "stack.h"
#include "solve.h"
#include "stock.h"
#include "game.h"

int passcnt, movecnt;

/* A blind solver, no backtracking */

int solve(int gather, int keepinit)
{
    char cn[1024];
    passcnt= 1;
    movecnt= 0;
    while (!victory())
    {
	for (int i= 0; i < nsrc; i++)
	{
	    int index1, len;
	    Stack *s= stacks+srclist[i];
	    for (int rc= s->firstMove(s, &index1, &len); rc;
		    rc= s->nextMove(s, &index1, &len))
	    {
		for (int j= 0; j < ndst; j++)
		{
		    Stack *d= stacks+dstlist[j];
		    if (s == d) continue;
		    if (d->mayInsert(d, s->c[index1], len, s))
		    {
			/* Move the cards */
			if (verbose > 1) cn[0]= '\0';
			for (int i= index1; i < index1+len; i++)
			{
			    Card *c= s->c[i];
			    pushStack(d,c);
			    if (verbose > 1)
			    {
				if (cn[0] != '\0') strcat(cn," ");
				strcat(cn,cardname(c));
			    }
			}
			removeStack(s, index1, len);

			/* Turn new top card of source stack face up */
			Card *c= topStack(s);
			if (c) c->faceup= 1;

			movecnt++;

			if (s->postMove) s->postMove(s);

			if (verbose > 1)
			    printf("%3d: [%s] %c%02d -> %c%02d\n",movecnt, cn,
				TYPECHAR[s->type], s->tid+1,
				TYPECHAR[d->type], d->tid+1);

			goto nextstep;
		    }
		}
	    }
	}

	/* Found no moves - try dealing a card from stock */
	if (!dealStock(0, NULL, NULL))
	{
	    if (verbose > 1 && verbose <= 4) printState(stdout, stacks);
	    if (verbose > 0)
		printf("Stuck! pass=%d moves=%d\n",passcnt,movecnt);
	    if (gather) gatherAll();
	    return 0;
	}

	nextstep:;

	if (verbose > 4) printState(stdout, stacks);
    }
    if (verbose > 0)
	printf("Victory! pass=%d moves=%d\n",passcnt,movecnt);
    if (gather) gatherAll();
    return 1;
}
